/**
 * 
 */
package com.longcai.fenzhuang.fuyou;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;



/**
 * @author Administrator
 * 
 */
public class FuiouHttpPoster {

	public FuiouHttpPoster() {
	}

	private String url;

	private String charset;

	public void setUrl(String url) {
		this.url = url;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

	public FuiouHttpPoster(String url, String charset) {
		super();
		this.url = url;
		this.charset = charset;
	}

	public FuiouHttpPoster(String url) {
		super();
		this.url = url;
		this.charset = Charset.defaultCharset().name();
	}
	
	
	
	public String newPost(final String body) throws Exception {
		return post(new PostMethodCallback() {

			public void doInPostMethod(PostMethod postMethod) {

				try {
					postMethod.setRequestEntity(new StringRequestEntity(body,"application/json","UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	

	/**
	 * 使用http协议发送xmltext到url
	 * 
	 * @param url
	 *            将要发送的地址
	 * @param xmltext
	 *            将要发送的内容
	 * @return http返回码
	 * @throws LoanException
	 * @throws Exception
	 */
	private String post(PostMethodCallback callback) throws Exception {
		PostMethod xmlpost = null;
		HttpClient httpclient = new HttpClient();
		try {
			// https设置
			if (url.indexOf("https://") != -1) {
				// 创建SSL连接
				@SuppressWarnings("deprecation")
				Protocol myhttps = new Protocol("https",new MySSLSocketFactory(), 443);
				Protocol.registerProtocol("https", myhttps);
			}	
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(60 * 1000);
			httpclient.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
			xmlpost = new PostMethod(url);
			httpclient.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
			httpclient.getParams().setContentCharset(charset);
			// xmlpost.setRequestHeader("content-type", "text/xml; charset=" +
			// charset);

			// 内部回调，发送数据，设置参数用
			callback.doInPostMethod(xmlpost);
			// 执行请求
			httpclient.executeMethod(xmlpost);

			// 获取返回信息
			InputStream ips = xmlpost.getResponseBodyAsStream();
			List<Byte> byteList = new ArrayList<Byte>();

			int is = 0;
			while ((is = ips.read()) != -1)
				byteList.add((byte) is);

			byte[] allb = new byte[byteList.size()];
			for (int j = 0; j < byteList.size(); j++)
				allb[j] = byteList.get(j);
			String responseString = new String(allb, charset);
			// LogWriter.debug(this, "HTTP返回码=" + responseStatCode);
			System.out.println("应答数据=" + responseString);

			if (url.indexOf("https://") != -1)
				Protocol.unregisterProtocol("https");
			return responseString;
		} catch (IOException ex2) {
			ex2.printStackTrace();
			System.out.println("报文发送到[" + url + "]失败:" + ex2.getMessage());
			throw new Exception("报文发送异常");
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("报文发送到[" + url + "]失败:" + ex.getMessage());
			throw new Exception("报文发送异常");
		} finally {
			try {
				if(xmlpost != null)
					xmlpost.releaseConnection();
				if(httpclient != null)
					httpclient.getHttpConnectionManager().closeIdleConnections(0);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void sendPostComplexData(final String url, final Map<String, String> params,
			final File data) {
		new Thread(new Runnable() {
			public void run() {
				HttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager();
				// 过时，用Builder代替可以加一些开关
				org.apache.http.client.HttpClient httpClient = HttpClientBuilder.create()
						.setConnectionManager(httpClientConnectionManager)
						.build();

				HttpPost httpPost = new HttpPost(url);
				HttpResponse response = null;
				MultipartEntityBuilder builder = MultipartEntityBuilder
						.create();
				if (params != null && !params.isEmpty()) {
					for (Map.Entry<String, String> entry : params.entrySet()) {
						builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("text/plain", Consts.UTF_8));// 增加文本内容
					}
					builder.addBinaryBody("papersFile", data);// 增加字节内容，第二个参数可以是File,byte[],InputStream
					httpPost.setEntity(builder.build());
				}
				// 完成所有表单的操作
				try {
					response = httpClient.execute(httpPost);
					if (response.getStatusLine().getStatusCode() == 200) {
						// 取回服务器端的响应结果
						String result = EntityUtils.toString(
								response.getEntity(), Consts.UTF_8);
						System.out.println("返回信息=======>>>>>>>>" + result);
						//callBack.getResult(result);
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (httpClient != null) {
						// httpClient.getConnectionManager().shutdown();
						// 用自己加上去的Manager
						httpClientConnectionManager.shutdown();
					}
				}
			}
		}).start();
	}

	/**
	 * PostMethod回调处理
	 * 
	 */
	public interface PostMethodCallback {
		public void doInPostMethod(PostMethod postMethod);
	}

}
